package kp.rpc.protocol.encode;

import io.vertx.core.buffer.Buffer;
import kp.rpc.Enum.ProtocolMessageSerializerEnum;
import kp.rpc.protocol.ProtocolMessage;
import kp.rpc.serializer.Serializer;
import kp.rpc.serializer.factory.SerializerFactory;
import kp.rpc.utils.JsonUtil;

import java.io.IOException;

public class ProtocolMessageEncoder {
    /**
     * @param protocolMessage 控制消息
     * @return byte[]
     * @description: 编码器
     * @author tzf
     * @date: 2024/6/6 15:23
     */

    public static Buffer encode(ProtocolMessage<?> protocolMessage) throws IOException {
        if (protocolMessage == null || protocolMessage.getHeader() == null) {
            return Buffer.buffer();
        }
        // 获取头信息
        ProtocolMessage.Header header = protocolMessage.getHeader();
        //依次向缓冲区写入字节
        Buffer buffer = Buffer.buffer();
        buffer.appendByte(header.getMagic());
        buffer.appendByte(header.getVersion());
        buffer.appendByte(header.getSerializer());
        buffer.appendByte(header.getType());
        buffer.appendByte(header.getStatus());
        buffer.appendLong(header.getRequestId());
        //获取序列化器
        ProtocolMessageSerializerEnum serializerByKey = ProtocolMessageSerializerEnum.getEnumByKey(header.getSerializer());
        if (serializerByKey == null) {
            throw new RuntimeException("未找到序列化器");
        }
        Serializer serializerKey = SerializerFactory.getInstance(serializerByKey.getValue());
        byte[] serializeBytes = serializerKey.serialize(protocolMessage.getBody());
        //设置消息体的长度
        buffer.appendInt(serializeBytes.length);
        return buffer.appendBytes(serializeBytes);
    }
}
